package top.jolyoulu.modules.poimodule.excel.reader.handler.sheet;

import lombok.extern.slf4j.Slf4j;
import top.jolyoulu.modules.poimodule.excel.reader.handler.ExcelReaderHandler;

import java.util.List;
import java.util.function.Consumer;

/**
 * @Author: JolyouLu
 * @Date: 2023/12/17 16:46
 * @Description 处理每一个单元格的Handler
 */
@Slf4j
public class SliceSheetReaderHandler<T> extends AbsSheetReaderHandler<T> implements ExcelReaderHandler<String> {

    private final Integer size;

    private final Consumer<List<T>> consumer;

    public SliceSheetReaderHandler(Class<T> dataType, Integer size, Consumer<List<T>> consumer) {
        super(dataType);
        this.size = size;
        this.consumer = consumer;
    }

    public SliceSheetReaderHandler(AbsSheetReaderHandler<T> readerHandler, Integer size, Consumer<List<T>> consumer) {
        super(readerHandler.dataType);
        super.setStartRow(readerHandler.startRow);
        this.size = size;
        this.consumer = consumer;
    }

    @Override
    protected T handlerRow(Integer row, Integer column, String value) {
        //达到了某个分页
        int currentLine = row - startRow;
        if (currentLine > 0 && currentLine % size == 0) {
            consumer.accept(super.getData());
            //清理掉已处理的数据
            super.getData().clear();
        }
        try {
            return dataType.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("SaxCellHandler构建返回对象失败", e);
        }
    }
}
